// SmartInput Chrome扩展内容脚本

// 使用统一的日志系统
// 直接使用全局的SmartInputLogger实例，避免重复声明
// logger 变量由 logger.js 文件提供，通过 window.SmartInputLogger 访问

class SmartInputContent {
  constructor() {
    this.isActive = false;
    this.currentInput = null;
    this.voiceIndicator = null;
    this.syncIndicator = null;
    this.floatingPanel = null;
    
    // 语音预览相关
    this.currentVoicePreview = null;
    this.previewTargetElement = null;
    
    // 初始化增强的输入框支持
    // 直接使用备用方案，避免EnhancedInputSupport未定义的错误
    logger.info('使用备用EnhancedInputSupport方案');
    this.enhancedInput = {
        async insertText(input, text) {
          if (!input || !text) return false;
          
          try {
            // 检查是否是Reddit搜索框
            const isRedditSearch = input.name === 'q' || input.placeholder?.includes('Search');
            
            if (isRedditSearch) {
              logger.debug('使用Reddit专用方法...');
              input.focus();
              input.click();
              input.select();
              document.execCommand('delete', false);
              const success = document.execCommand('insertText', false, text);
              
              if (success) {
                this.triggerEvents(input, ['input', 'change']);
                logger.success('Reddit专用方法插入成功');
                return true;
              }
            }
            
            // 标准输入框方法
            if (input.tagName === 'TEXTAREA' || 
                input.type === 'text' || 
                input.type === 'search' || 
                input.type === 'email' || 
                input.type === 'url' || 
                input.type === 'tel' || 
                input.type === 'password') {
              
              const start = input.selectionStart || 0;
              const end = input.selectionEnd || 0;
              const value = input.value || '';
              
              input.value = value.substring(0, start) + text + value.substring(end);
              
              const newPosition = start + text.length;
              input.selectionStart = newPosition;
              input.selectionEnd = newPosition;
              
              this.triggerEvents(input, ['input', 'change']);
              logger.success('标准输入框方法插入成功');
              return true;
            }
            
            // contentEditable 元素
            else if (input.contentEditable === 'true' || input.contentEditable === '') {
              document.execCommand('insertText', false, text);
              this.triggerEvents(input, ['input', 'change']);
              logger.success('contentEditable方法插入成功');
              return true;
            }
            
            return false;
          } catch (error) {
            logger.error('文字插入过程中发生错误:', error);
            return false;
          }
        },
        
        findInputFields() {
          const inputs = [];
          const selectors = [
            // 标准HTML输入框
            'input[type="text"]:not([disabled]):not([readonly])',
            'input[type="search"]:not([disabled]):not([readonly])',
            'input[type="email"]:not([disabled]):not([readonly])',
            'input[type="url"]:not([disabled]):not([readonly])',
            'input[type="tel"]:not([disabled]):not([readonly])',
            'input[type="password"]:not([disabled]):not([readonly])',
            'input[type="number"]:not([disabled]):not([readonly])',
            'input:not([type]):not([disabled]):not([readonly])',
            
            // 文本区域
            'textarea:not([disabled]):not([readonly])',
            
            // 富文本编辑器
            '[contenteditable="true"]:not([disabled])',
            '[contenteditable=""]:not([disabled])',
            
            // 角色标识
            '[role="textbox"]:not([disabled])',
            '[role="searchbox"]:not([disabled])',
            
            // 自定义类名
            '.input-field:not([disabled]):not([readonly])',
            '.search-input:not([disabled]):not([readonly])',
            '.form-control:not([disabled]):not([readonly])',
            '.form-input:not([disabled]):not([readonly])',
            '.text-input:not([disabled]):not([readonly])',
            '.input-box:not([disabled]):not([readonly])',
            '.search-box:not([disabled]):not([readonly])',
            '.editable:not([disabled])',
            
            // 特殊网站选择器
            'input[name="q"]:not([disabled]):not([readonly])',
            'input[placeholder*="Search"]:not([disabled]):not([readonly])',
            'input[placeholder*="搜索"]:not([disabled]):not([readonly])'
          ];
          
          selectors.forEach(selector => {
            try {
              const elements = document.querySelectorAll(selector);
              elements.forEach(el => {
                if (this.isVisibleAndEditable(el)) {
                  inputs.push(el);
                }
              });
            } catch (error) {
              logger.log('选择器失败:', selector, error);
            }
          });
          
          return inputs;
        },
        
        isVisibleAndEditable(element) {
          const style = window.getComputedStyle(element);
          const rect = element.getBoundingClientRect();
          
          return style.display !== 'none' && 
                 style.visibility !== 'hidden' && 
                 style.opacity !== '0' &&
                 rect.width > 0 && 
                 rect.height > 0;
        },
        
        triggerEvents(element, eventTypes) {
          eventTypes.forEach(eventType => {
            try {
              const event = new Event(eventType, { bubbles: true, cancelable: true });
              element.dispatchEvent(event);
            } catch (error) {
              logger.log(`事件触发失败 ${eventType}:`, error);
            }
          });
        }
      };
    
    this.init();
  }
  
  init() {
    logger.info('SmartInput内容脚本初始化...', window.location.href);
    
    // 检查是否已经初始化过
    if (window.smartInputInitialized) {
      logger.info('SmartInput已经初始化过，跳过重复初始化');
      return;
    }
    
    try {
      // 立即设置消息监听器，确保能接收消息
      this.setupEventListeners();
      logger.info('事件监听器设置完成');
      
      // 创建浮动面板
      this.createFloatingPanel();
      logger.info('浮动面板创建完成');
      
      // 注入样式
      this.injectStyles();
      logger.info('样式注入完成');
      
      // 标记为已初始化
      window.smartInputInitialized = true;
      logger.info('标记为已初始化');
      
      // 通知后台脚本初始化完成
      try {
        chrome.runtime.sendMessage({ action: 'contentScriptReady' });
        logger.info('已发送初始化完成消息到后台脚本');
      } catch (error) {
        logger.log('无法发送初始化完成消息:', error);
      }
      
      logger.info('SmartInput内容脚本初始化完成');
    } catch (error) {
      logger.error('SmartInput内容脚本初始化失败:', error);
    }
  }
  
  setupEventListeners() {
    // 监听来自background script的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      this.handleMessage(request, sender, sendResponse);
    });
    
    // 监听页面点击事件
    document.addEventListener('click', (event) => {
      this.handlePageClick(event);
    });
    
    // 监听输入框焦点事件
    document.addEventListener('focusin', (event) => {
      this.handleInputFocus(event);
    });
    
    // 监听输入框失焦事件
    document.addEventListener('focusout', (event) => {
      this.handleInputBlur(event);
    });
    
    // 监听键盘事件
    document.addEventListener('keydown', (event) => {
      this.handleKeyDown(event);
    });
    
    // 监听页面加载完成
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        this.onPageLoaded();
      });
    } else {
      this.onPageLoaded();
    }
    
    // 监听页面完全加载
    window.addEventListener('load', () => {
      logger.info('页面完全加载完成，重新扫描输入框');
      this.scanInputFields();
    });
  }
  
  handleMessage(request, sender, sendResponse) {
    logger.info('内容脚本收到消息:', request.action, request);
    
    switch (request.action) {
      case 'pageLoaded':
        this.onPageLoaded(request);
        break;
        
      case 'mobileTextInput':
        this.handleMobileTextInput(request).then(result => {
          logger.info('手机端文字输入处理完成:', result);
          sendResponse(result);
        }).catch(error => {
          logger.error('处理手机端文字输入失败:', error);
          sendResponse({ 
            success: false, 
            inserted: false, 
            error: error.message 
          });
        });
        return true; // 保持消息通道开放
        break;
        
      case 'voiceRecognitionPreview':
        this.handleVoiceRecognitionPreview(request).then(result => {
          logger.info('语音识别预览处理完成:', result);
          sendResponse(result);
        }).catch(error => {
          logger.error('处理语音识别预览失败:', error);
          sendResponse({ 
            success: false, 
            error: error.message 
          });
        });
        return true; // 保持消息通道开放
        break;
        
      case 'debugTest':
        logger.info('收到调试测试消息:', request);
        sendResponse({ 
          success: true, 
          received: true, 
          timestamp: Date.now(),
          initialized: window.smartInputInitialized,
          smartInputContent: typeof SmartInputContent
        });
        break;
        
      case 'showPageNotification':
        logger.info('显示页面通知:', request.title, request.message);
        this.showPageNotification(request.title, request.message);
        sendResponse({ success: true });
        break;
        
      default:
        logger.log('未知的消息类型:', request.action);
        break;
    }
    
    // 确保发送响应
    if (sendResponse) {
      sendResponse({ success: true });
    }
  }
  
  onPageLoaded(data = {}) {
    logger.info('页面加载完成:', data.url || window.location.href);
    
    // 扫描页面中的输入框
    this.scanInputFields();
    
    // 显示浮动面板
    this.showFloatingPanel();
  }
  
  scanInputFields() {
    // 使用增强的输入框支持
    const inputs = this.enhancedInput.findInputFields();
    logger.info('增强输入框扫描找到数量:', inputs.length);
    
    inputs.forEach((input, index) => {
      // 跳过已经处理过的输入框
      if (input.getAttribute('data-smartinput') === 'true') {
        return;
      }
      
      // 添加SmartInput标识
      input.setAttribute('data-smartinput', 'true');
      
      logger.info(`处理输入框 ${index + 1}:`, input.tagName, input.type, input.className);
      
      // 添加语音输入按钮
      this.addVoiceButton(input);
    });
    
    logger.info('增强输入框扫描完成');
  }
  
  addVoiceButton(input) {
    // 移除语音按钮功能
    return;
  }
  
  handlePageClick(event) {
    // 检查是否点击了SmartInput相关元素
    if (event.target.closest('.smartinput-voice-btn') ||
        event.target.closest('.smartinput-panel')) {
      return;
    }
    
    // 隐藏浮动面板
    this.hideFloatingPanel();
  }
  
  handleInputFocus(event) {
    const input = event.target;
    if (input.getAttribute('data-smartinput') === 'true') {
      this.currentInput = input;
      
      // 显示插件激活提示
      this.showPluginActivationTip(input);
      
      // this.showVoiceIndicator(); // 移除语音指示器功能
    }
  }
  
  // 显示插件激活提示
  showPluginActivationTip(input) {
    // 防抖处理：如果提示刚显示过，则不重复显示
    if (this.lastTipTime && Date.now() - this.lastTipTime < 2000) {
      return;
    }
    
    // 移除已存在的提示
    this.removePluginActivationTip();
    
    // 记录显示时间
    this.lastTipTime = Date.now();
    
    // 创建提示元素
    const tip = document.createElement('div');
    tip.className = 'smartinput-activation-tip';
    tip.innerHTML = `
      <div class="tip-content">
        <div class="tip-header">
          <span class="tip-icon">🎯</span>
          <span class="tip-text">SmartInput 已激活</span>
        </div>
        <div class="tip-body">
          <span class="tip-subtitle">语音输入功能可用</span>
          <span class="tip-desc">点击输入框即可使用</span>
        </div>
      </div>
    `;
    
    // 设置基础样式 - 固定在右上角
    tip.style.cssText = `
      position: fixed;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 10px 16px;
      border-radius: 16px;
      font-size: 13px;
      font-weight: 500;
      box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
      z-index: 2147483647;
      opacity: 0;
      transform: translateX(100%) scale(0.9);
      transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
      pointer-events: none;
      white-space: nowrap;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      min-width: 180px;
      max-width: 240px;
      text-align: center;
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.2);
      top: 20px;
      right: 20px;
      box-sizing: border-box;
    `;
    
    // 添加到页面
    document.body.appendChild(tip);
    
    // 等待DOM更新后显示动画
    setTimeout(() => {
      try {
        // 显示动画 - 从右侧滑入
        tip.style.opacity = '1';
        tip.style.transform = 'translateX(0) scale(1)';
        
        // 添加调试信息
        if (window.SmartInputLogger && window.SmartInputLogger.debug) {
          window.SmartInputLogger.debug('插件激活提示已显示在右上角');
        }
        
      } catch (error) {
        if (window.SmartInputLogger && window.SmartInputLogger.error) {
          window.SmartInputLogger.error('显示提示动画失败:', error);
        }
        // 使用默认显示
        tip.style.opacity = '1';
        tip.style.transform = 'translateX(0) scale(1)';
      }
    }, 0);
    
    // 3秒后自动隐藏
    setTimeout(() => {
      this.removePluginActivationTip();
    }, 3000);
    
    // 保存提示引用
    this.currentActivationTip = tip;
  }
  
  // 移除插件激活提示
  removePluginActivationTip() {
    if (this.currentActivationTip) {
      this.currentActivationTip.style.opacity = '0';
      this.currentActivationTip.style.transform = 'translateY(-10px)';
      
      setTimeout(() => {
        if (this.currentActivationTip && this.currentActivationTip.parentNode) {
          this.currentActivationTip.parentNode.removeChild(this.currentActivationTip);
        }
        this.currentActivationTip = null;
      }, 300);
    }
  }
  
  handleInputBlur(event) {
    const input = event.target;
    if (input === this.currentInput) {
      this.currentInput = null;
      
      // 隐藏插件激活提示
      this.removePluginActivationTip();
      
      // this.hideVoiceIndicator(); // 移除语音指示器功能
    }
  }
  
  handleKeyDown(event) {
    // 移除快捷键功能
    return;
  }
  
  startVoiceInput(input) {
    // 移除语音输入功能
    return;
  }
  
  handleVoiceResult(data) {
    // 移除语音结果处理功能
    return;
  }
  
  handleSyncedText(data) {
    // 移除同步文字处理功能
    return;
  }
  
  async handleMobileTextInput(data) {
    const { text, source, timestamp } = data;
    
    logger.info('收到手机端文字输入:', { text, source, timestamp });
    
    // 如果是最终的语音识别结果，先清除预览
    if (source && source.includes('voice_recognition')) {
      this.clearVoicePreview();
    }
    
    // 显示通知
    this.showNotification(`收到来自手机端的文字: ${text.substring(0, 30)}${text.length > 30 ? '...' : ''}`);
    
    // 检查当前输入框状态
    logger.info('当前输入框状态:', {
      hasCurrentInput: !!this.currentInput,
      currentInput: this.currentInput ? {
        tagName: this.currentInput.tagName,
        type: this.currentInput.type,
        id: this.currentInput.id,
        className: this.currentInput.className
      } : null,
      activeElement: document.activeElement ? {
        tagName: document.activeElement.tagName,
        type: document.activeElement.type || '',
        id: document.activeElement.id,
        className: document.activeElement.className
      } : null
    });
    
    let inserted = false;
    let targetType = null;
    
    // 如果当前有输入框聚焦，直接插入文字
    if (this.currentInput) {
      logger.info('使用当前输入框插入文字');
      try {
        await this.insertText(text);
        inserted = true;
        targetType = this.currentInput.tagName;
        this.showNotification('文字已插入到当前输入框');
      } catch (error) {
        logger.error('插入失败:', error);
        inserted = false;
      }
    } else {
      logger.info('没有当前输入框，尝试自动查找');
      // 尝试自动找到合适的输入框
      const autoInput = this.findBestInputField();
      if (autoInput) {
        logger.info('自动找到输入框:', {
          tagName: autoInput.tagName,
          type: autoInput.type,
          id: autoInput.id,
          className: autoInput.className
        });
        this.currentInput = autoInput;
        try {
          await this.insertText(text);
          inserted = true;
          targetType = autoInput.tagName;
          this.showNotification('文字已自动插入到找到的输入框');
        } catch (error) {
          logger.error('插入失败:', error);
          inserted = false;
        }
      } else {
        logger.info('没有找到合适的输入框');
        // 直接尝试插入到当前焦点元素或页面
        const activeElement = document.activeElement;
        if (activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA' || activeElement.contentEditable === 'true')) {
          logger.info('插入到当前焦点元素');
          this.currentInput = activeElement;
          try {
            await this.insertText(text);
            inserted = true;
            targetType = activeElement.tagName;
            this.showNotification('文字已插入到当前焦点元素');
          } catch (error) {
            logger.error('插入失败:', error);
            inserted = false;
          }
        } else {
          logger.info('尝试插入到页面');
          // 尝试插入到页面中第一个可编辑的元素
          const firstEditable = document.querySelector('input, textarea, [contenteditable="true"]');
          if (firstEditable) {
            logger.info('插入到第一个可编辑元素');
            this.currentInput = firstEditable;
            try {
              await this.insertText(text);
              inserted = true;
              targetType = firstEditable.tagName;
              this.showNotification('文字已插入到页面');
            } catch (error) {
              logger.error('插入失败:', error);
              inserted = false;
            }
          } else {
            logger.info('无法找到可插入的位置');
            this.showNotification('无法找到合适的插入位置');
            inserted = false;
          }
        }
      }
    }
    
    // 返回插入结果
    return {
      success: true,
      inserted: inserted,
      targetType: targetType,
      text: text
    };
  }
  
  async handleVoiceRecognitionPreview(data) {
    const { text, source, timestamp } = data;
    
    logger.info('收到语音识别实时预览:', { text, source, timestamp });
    
    // 实时预览：在当前输入框显示临时文本，但不实际插入
    try {
      const targetElement = this.currentInput || document.activeElement || this.findBestInputField();
      
      if (targetElement && this.isEditableElement(targetElement)) {
        // 显示实时预览
        this.showVoicePreview(targetElement, text);
        
        // 显示预览通知
        this.showNotification(`🎤 识别中: ${text.substring(0, 20)}${text.length > 20 ? '...' : ''}`, 'preview');
        
        return {
          success: true,
          previewed: true,
          targetType: targetElement.tagName
        };
      } else {
        logger.info('没有找到合适的预览位置');
        return {
          success: false,
          previewed: false,
          error: '没有找到合适的预览位置'
        };
      }
    } catch (error) {
      logger.error('语音识别预览失败:', error);
      return {
        success: false,
        previewed: false,
        error: error.message
      };
    }
  }
  
  findBestInputField() {
    // 使用增强的输入框支持查找最佳输入框
    const inputs = this.enhancedInput.findInputFields();
    
    if (inputs.length === 0) {
      logger.info('没有找到合适的输入框');
      return null;
    }
    
    // 按优先级排序
    const sortedInputs = inputs.sort((a, b) => {
      const scoreA = this.getInputScore(a);
      const scoreB = this.getInputScore(b);
      return scoreB - scoreA;
    });
    
    const bestInput = sortedInputs[0];
    logger.info('找到最佳输入框:', bestInput.tagName, bestInput.type, bestInput.className);
    return bestInput;
  }
  
  getInputScore(element) {
    let score = 0;

    // 基础分数
    if (element.tagName === 'INPUT') score += 10;
    if (element.tagName === 'TEXTAREA') score += 8;
    if (element.contentEditable) score += 6;

    // 类型分数
    if (element.type === 'text') score += 5;
    if (element.type === 'search') score += 4;
    if (element.type === 'email') score += 3;

    // 可见性分数
    const rect = element.getBoundingClientRect();
    if (rect.width > 100 && rect.height > 20) score += 3;
    if (rect.width > 200 && rect.height > 30) score += 2;

    // 焦点分数
    if (document.activeElement === element) score += 5;
    if (element.autofocus) score += 3;

    // 特殊属性分数
    if (element.name === 'q') score += 4;
    if (element.placeholder && element.placeholder.includes('Search')) score += 3;
    if (element.getAttribute('role') === 'textbox') score += 2;

    return score;
  }
  
  async insertText(text) {
    if (!this.currentInput) return;
    
    const input = this.currentInput;
    logger.info('尝试插入文字到元素:', {
      tagName: input.tagName,
      type: input.type,
      className: input.className,
      id: input.id,
      name: input.name
    });
    
    try {
      // 使用增强的输入框支持插入文本
      const success = await this.enhancedInput.insertText(input, text);
      
      if (success) {
        logger.success('增强输入框支持插入成功:', text);
        
        // 显示成功通知
        this.showNotification(`成功插入: ${text.substring(0, 30)}${text.length > 30 ? '...' : ''}`);
      } else {
        logger.log('增强输入框支持插入失败，尝试备用方法');
        
        // 备用方法：使用原有的插入逻辑
        await this.fallbackInsertText(input, text);
      }
      
    } catch (error) {
      logger.error('插入文字失败:', error);
      await this.fallbackInsertText(input, text);
    }
  }
  
  // 备用插入方法
  async fallbackInsertText(input, text) {
    try {
      // 确保元素聚焦
      if (document.activeElement !== input) {
        input.focus();
        await new Promise(resolve => setTimeout(resolve, 100));
      }
      
      // 检查是否是Reddit搜索框
      const isRedditSearch = input.name === 'q' || input.placeholder?.includes('Search');
      
      if (isRedditSearch) {
        logger.log('使用Reddit专用方法...');
        input.focus();
        input.click();
        input.select();
        document.execCommand('delete', false);
        const success = document.execCommand('insertText', false, text);
        
        if (success) {
          this.triggerEvents(input, ['input', 'change']);
          logger.success('Reddit备用方法插入成功');
          return;
        }
      }
      
      // 标准输入框方法
      if (input.tagName === 'TEXTAREA' || 
          input.type === 'text' || 
          input.type === 'search' || 
          input.type === 'email' || 
          input.type === 'url' || 
          input.type === 'tel' || 
          input.type === 'password') {
        
        const start = input.selectionStart || 0;
        const end = input.selectionEnd || 0;
        const value = input.value || '';
        
        input.value = value.substring(0, start) + text + value.substring(end);
        
        const newPosition = start + text.length;
        input.selectionStart = newPosition;
        input.selectionEnd = newPosition;
        
        this.triggerEvents(input, ['input', 'change']);
        logger.success('标准输入框备用方法插入成功');
      }
      // contentEditable 元素
      else if (input.contentEditable === 'true' || input.contentEditable === '') {
        document.execCommand('insertText', false, text);
        this.triggerEvents(input, ['input', 'change']);
        logger.success('contentEditable备用方法插入成功');
      }
      // 通用方法
      else {
        if (input.value !== undefined) {
          input.value = (input.value || '') + text;
        } else if (input.textContent !== undefined) {
          input.textContent = (input.textContent || '') + text;
        }
        
        this.triggerEvents(input, ['input', 'change']);
        logger.success('通用备用方法插入成功');
      }
      
    } catch (error) {
      logger.error('备用插入方法也失败:', error);
    }
  }
  
  // 触发事件
  triggerEvents(element, eventTypes) {
    eventTypes.forEach(eventType => {
      try {
        const event = new Event(eventType, { bubbles: true, cancelable: true });
        element.dispatchEvent(event);
      } catch (error) {
        logger.log('事件触发失败:', eventType, error);
      }
    });
  }
  
  syncCurrentText() {
    // 移除文字同步功能
    return;
  }
  
  createFloatingPanel() {
    this.floatingPanel = document.createElement('div');
    this.floatingPanel.className = 'smartinput-panel';
    this.floatingPanel.innerHTML = `
      <div class="smartinput-header">
        <span class="smartinput-title">SmartInput</span>
        <button class="smartinput-close">×</button>
      </div>
      <div class="smartinput-content">
        <button class="smartinput-btn settings-btn" title="设置">
          <span class="icon">⚙️</span>
          <span class="label">设置</span>
        </button>
      </div>
    `;
    
    // 只保留设置按钮的事件监听器
    this.floatingPanel.querySelector('.settings-btn').addEventListener('click', () => {
      chrome.runtime.openOptionsPage();
    });
    
    this.floatingPanel.querySelector('.smartinput-close').addEventListener('click', () => {
      this.hideFloatingPanel();
    });
    
    document.body.appendChild(this.floatingPanel);
  }
  
  showFloatingPanel() {
    if (this.floatingPanel) {
      this.floatingPanel.classList.remove('hidden');
    }
  }
  
  hideFloatingPanel() {
    if (this.floatingPanel) {
      this.floatingPanel.classList.add('hidden');
    }
  }
  
  showVoiceIndicator() {
    // 移除语音指示器功能
    return;
  }
  
  hideVoiceIndicator() {
    // 移除语音指示器功能
    return;
  }
  
  // 检查元素是否可编辑
  isEditableElement(element) {
    if (!element) return false;
    
    const tagName = element.tagName.toLowerCase();
    const type = element.type ? element.type.toLowerCase() : '';
    
    // 检查常见的可编辑元素
    if (tagName === 'textarea') return true;
    if (tagName === 'input' && ['text', 'email', 'password', 'search', 'url', 'tel'].includes(type)) return true;
    if (element.contentEditable === 'true') return true;
    if (element.isContentEditable) return true;
    
    return false;
  }
  
  // 显示语音预览（实时显示识别结果，不插入）
  showVoicePreview(element, text) {
    try {
      // 移除之前的预览
      this.clearVoicePreview();
      
      // 创建预览覆盖层
      const preview = document.createElement('div');
      preview.className = 'smartinput-voice-preview';
      preview.textContent = text;
      
      // 获取元素位置
      const rect = element.getBoundingClientRect();
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
      
      // 设置预览样式和位置
      preview.style.cssText = `
        position: absolute;
        top: ${rect.top + scrollTop + rect.height + 2}px;
        left: ${rect.left + scrollLeft}px;
        background: rgba(0, 123, 255, 0.9);
        color: white;
        padding: 8px 12px;
        border-radius: 4px;
        font-size: 14px;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
        z-index: 10000;
        max-width: 300px;
        word-wrap: break-word;
        white-space: pre-wrap;
        pointer-events: none;
        animation: fadeIn 0.2s ease-in;
      `;
      
      // 添加CSS动画
      if (!document.querySelector('#smartinput-preview-styles')) {
        const style = document.createElement('style');
        style.id = 'smartinput-preview-styles';
        style.textContent = `
          @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
          }
          .smartinput-voice-preview {
            transition: all 0.2s ease;
          }
        `;
        document.head.appendChild(style);
      }
      
      document.body.appendChild(preview);
      this.currentVoicePreview = preview;
      
      // 存储预览的元素引用，用于清理
      this.previewTargetElement = element;
      
      logger.info('✅ 语音预览已显示:', text);
      
    } catch (error) {
      logger.error('显示语音预览失败:', error);
    }
  }
  
  // 清除语音预览
  clearVoicePreview() {
    if (this.currentVoicePreview) {
      this.currentVoicePreview.remove();
      this.currentVoicePreview = null;
    }
    this.previewTargetElement = null;
  }
  
  showConfirmationDialog(text, message = '识别结果确认') {
    const dialog = document.createElement('div');
    dialog.className = 'smartinput-dialog';
    dialog.innerHTML = `
      <div class="smartinput-dialog-content">
        <h3>${message}</h3>
        <p class="smartinput-dialog-text">${text}</p>
        <div class="smartinput-dialog-buttons">
          <button class="smartinput-dialog-btn confirm-btn">确认</button>
          <button class="smartinput-dialog-btn cancel-btn">取消</button>
        </div>
      </div>
    `;
    
    dialog.querySelector('.confirm-btn').addEventListener('click', () => {
      this.insertText(text);
      dialog.remove();
    });
    
    dialog.querySelector('.cancel-btn').addEventListener('click', () => {
      dialog.remove();
    });
    
    document.body.appendChild(dialog);
  }
  
  showNotification(message, type = 'normal') {
    const notification = document.createElement('div');
    notification.className = `smartinput-notification ${type === 'preview' ? 'preview-notification' : ''}`;
    notification.textContent = message;
    
    // 如果是预览类型的通知，添加特殊样式
    if (type === 'preview') {
      notification.style.cssText += `
        background-color: rgba(0, 123, 255, 0.9) !important;
        border-left: 4px solid #007bff !important;
        opacity: 0.9;
      `;
    }
    
    document.body.appendChild(notification);
    
    // 预览通知持续时间较短，普通通知持续3秒
    const duration = type === 'preview' ? 1500 : 3000;
    setTimeout(() => {
      if (notification.parentNode) {
        notification.remove();
      }
    }, duration);
  }
  
  showPageNotification(title, message) {
    const notification = document.createElement('div');
    notification.className = 'smartinput-page-notification';
    notification.innerHTML = `
      <div class="smartinput-notification-title">${title}</div>
      <div class="smartinput-notification-message">${message}</div>
    `;
    
    // 添加样式
    notification.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      background: #333;
      color: white;
      padding: 15px;
      border-radius: 8px;
      font-size: 14px;
      z-index: 10000;
      box-shadow: 0 4px 12px rgba(0,0,0,0.3);
      max-width: 300px;
      word-wrap: break-word;
    `;
    
    document.body.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
      if (notification.parentNode) {
        notification.remove();
      }
    }, 3000);
  }
  
  injectStyles() {
    const style = document.createElement('style');
    style.textContent = `
      .smartinput-panel {
        position: fixed;
        top: 20px;
        right: 20px;
        background: white;
        border: 1px solid #ddd;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 10000;
        min-width: 200px;
      }
      
      .smartinput-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 15px;
        border-bottom: 1px solid #eee;
        background: #f8f9fa;
        border-radius: 8px 8px 0 0;
      }
      
      .smartinput-title {
        font-weight: bold;
        color: #333;
      }
      
      .smartinput-close {
        background: none;
        border: none;
        font-size: 18px;
        cursor: pointer;
        color: #666;
      }
      
      .smartinput-content {
        padding: 15px;
      }
      
      .smartinput-btn {
        display: flex;
        align-items: center;
        width: 100%;
        padding: 8px 12px;
        margin-bottom: 8px;
        background: #f8f9fa;
        border: 1px solid #ddd;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.2s;
      }
      
      .smartinput-btn:hover {
        background: #e9ecef;
      }
      
      .smartinput-btn .icon {
        margin-right: 8px;
        font-size: 16px;
      }
      
      .smartinput-btn .label {
        font-size: 14px;
        color: #333;
      }
      
      .smartinput-dialog {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10001;
      }
      
      .smartinput-dialog-content {
        background: white;
        padding: 20px;
        border-radius: 8px;
        max-width: 400px;
        width: 90%;
      }
      
      .smartinput-dialog-content h3 {
        margin: 0 0 15px 0;
        color: #333;
      }
      
      .smartinput-dialog-text {
        background: #f8f9fa;
        padding: 10px;
        border-radius: 4px;
        margin: 0 0 15px 0;
        word-break: break-all;
      }
      
      .smartinput-dialog-buttons {
        display: flex;
        gap: 10px;
        justify-content: flex-end;
      }
      
      .smartinput-dialog-btn {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
      }
      
      .confirm-btn {
        background: #007bff;
        color: white;
      }
      
      .cancel-btn {
        background: #6c757d;
        color: white;
      }
      
      .smartinput-voice-btn {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        background: none;
        border: none;
        cursor: pointer;
        font-size: 16px;
        opacity: 0.6;
        transition: opacity 0.2s;
        z-index: 1000;
      }
      
      .smartinput-voice-btn:hover {
        opacity: 1 !important;
      }
      
      .smartinput-input-relative {
        position: relative !important;
      }
      
      .smartinput-voice-indicator {
        position: fixed;
        top: 20px;
        right: 20px;
        background: #4CAF50;
        color: white;
        padding: 10px 15px;
        border-radius: 5px;
        font-size: 14px;
        z-index: 10000;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
      }
      
      .smartinput-notification {
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: #333;
        color: white;
        padding: 10px 20px;
        border-radius: 5px;
        font-size: 14px;
        z-index: 10000;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
      }
      
      .smartinput-panel.hidden {
        display: none !important;
      }

      .smartinput-activation-tip {
        position: fixed;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 10px 16px;
        border-radius: 16px;
        font-size: 13px;
        font-weight: 500;
        box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
        z-index: 2147483647;
        opacity: 0;
        transform: translateX(100%) scale(0.9);
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        pointer-events: none;
        white-space: nowrap;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        min-width: 180px;
        max-width: 240px;
        text-align: center;
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        top: 20px;
        right: 20px;
        box-sizing: border-box;
      }
    `;
    
    document.head.appendChild(style);
  }
}

// 防止重复初始化
if (window.smartInputInitialized) {
  logger.info('SmartInput已经初始化过，跳过重复初始化');
} else {
  // 创建全局SmartInputContent实例
  let globalSmartInput = null;
  
  // 立即设置消息监听器，确保能接收消息
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    logger.info('内容脚本收到消息（全局监听器）:', request.action, request);
    
    // 如果SmartInputContent还没有初始化，先处理基本消息
    if (!window.smartInputInitialized) {
      logger.info('SmartInputContent未初始化，使用全局消息处理');
      
      switch (request.action) {
        case 'mobileTextInput':
          logger.info('处理手机端文字输入（全局）:', request.text);
          
          // 尝试插入文字到当前焦点输入框或页面
          const activeElement = document.activeElement;
          let targetElement = null;
          
          logger.info('当前焦点元素:', activeElement ? {
            tagName: activeElement.tagName,
            type: activeElement.type,
            id: activeElement.id,
            className: activeElement.className,
            contentEditable: activeElement.contentEditable
          } : 'null');
          
          // 首先检查当前焦点元素
          if (activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA' || activeElement.contentEditable === 'true')) {
            targetElement = activeElement;
            logger.info('使用当前焦点元素:', targetElement.tagName, targetElement.type);
          } else {
            logger.info('当前焦点元素不适合，开始查找其他输入框...');
            
            // 尝试找到页面中的第一个可编辑元素
            const selectors = [
              // 专门针对Reddit等网站的搜索框
              'input[name="q"]:not([disabled]):not([readonly])',
              'input[placeholder*="Search"]:not([disabled]):not([readonly])',
              'input[placeholder*="搜索"]:not([disabled]):not([readonly])',
              // 通用选择器
              'input[type="text"]:not([disabled]):not([readonly])',
              'input[type="search"]:not([disabled]):not([readonly])',
              'textarea:not([disabled]):not([readonly])',
              'input:not([type]):not([disabled]):not([readonly])',
              '[contenteditable="true"]:not([disabled])'
            ];
            
            logger.info('开始使用选择器查找输入框...');
            for (let i = 0; i < selectors.length; i++) {
              const selector = selectors[i];
              logger.info(`尝试选择器 ${i + 1}: ${selector}`);
              
              const elements = document.querySelectorAll(selector);
              logger.info(`找到 ${elements.length} 个元素`);
              
              for (let j = 0; j < elements.length; j++) {
                const element = elements[j];
                const style = window.getComputedStyle(element);
                const rect = element.getBoundingClientRect();
                
                logger.info(`检查元素 ${j + 1}:`, {
                  tagName: element.tagName,
                  type: element.type,
                  id: element.id,
                  className: element.className,
                  display: style.display,
                  visibility: style.visibility,
                  opacity: style.opacity,
                  width: rect.width,
                  height: rect.height,
                  visible: style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0',
                  hasSize: rect.width > 0 && rect.height > 0
                });
                
                if (style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0') {
                  if (rect.width > 0 && rect.height > 0) {
                    targetElement = element;
                    logger.info('✅ 找到合适的可编辑元素:', element.tagName, element.type, element.className);
                    break;
                  } else {
                    logger.info('❌ 元素不可见（尺寸为0）');
                  }
                } else {
                  logger.info('❌ 元素不可见（CSS隐藏）');
                }
              }
              if (targetElement) break;
            }
            
            if (!targetElement) {
              logger.info('❌ 没有找到任何合适的输入框');
            }
          }
          
          if (targetElement) {
            try {
              // 聚焦元素
              targetElement.focus();
              logger.info('✅ 元素聚焦成功');
              
              // 直接插入文字，不依赖SmartInputContent实例
              const insertTextDirectly = async (element, text) => {
                try {
                  // 检查是否是Reddit搜索框
                  const isRedditSearch = element.name === 'q' || element.placeholder?.includes('Search');
                  
                  if (isRedditSearch) {
                    logger.log('使用Reddit专用方法...');
                    element.focus();
                    element.click();
                    element.select();
                    document.execCommand('delete', false);
                    const success = document.execCommand('insertText', false, text);
                    
                    if (success) {
                      // 触发必要的事件
                      const inputEvent = new Event('input', { bubbles: true, cancelable: true });
                      element.dispatchEvent(inputEvent);
                      const changeEvent = new Event('change', { bubbles: true, cancelable: true });
                      element.dispatchEvent(changeEvent);
                      logger.success('Reddit专用方法插入成功');
                      return true;
                    }
                  }
                  
                  // 标准输入框方法
                  if (element.tagName === 'TEXTAREA' || 
                      element.type === 'text' || 
                      element.type === 'search' || 
                      element.type === 'email' || 
                      element.type === 'url' || 
                      element.type === 'tel' || 
                      element.type === 'password') {
                    
                    const start = element.selectionStart || 0;
                    const end = element.selectionEnd || 0;
                    const value = element.value || '';
                    
                    element.value = value.substring(0, start) + text + value.substring(end);
                    
                    const newPosition = start + text.length;
                    element.selectionStart = newPosition;
                    element.selectionEnd = newPosition;
                    
                    // 触发必要的事件
                    const inputEvent = new Event('input', { bubbles: true, cancelable: true });
                    element.dispatchEvent(inputEvent);
                    const changeEvent = new Event('change', { bubbles: true, cancelable: true });
                    element.dispatchEvent(changeEvent);
                    logger.success('标准输入框方法插入成功');
                    return true;
                  }
                  
                  // contentEditable 元素
                  else if (element.contentEditable === 'true' || element.contentEditable === '') {
                    document.execCommand('insertText', false, text);
                    const inputEvent = new Event('input', { bubbles: true, cancelable: true });
                    element.dispatchEvent(inputEvent);
                    const changeEvent = new Event('change', { bubbles: true, cancelable: true });
                    element.dispatchEvent(changeEvent);
                    logger.success('contentEditable方法插入成功');
                    return true;
                  }
                  
                  return false;
                } catch (error) {
                  logger.error('❌ 文字插入过程中发生错误:', error);
                  return false;
                }
              };
              
              // 执行插入
              insertTextDirectly(targetElement, request.text).then((success) => {
                if (success) {
                  logger.info('✅ 文字插入成功');
                } else {
                  logger.info('❌ 文字插入失败');
                }
              });
              
            } catch (insertError) {
              logger.error('❌ 文字插入过程中发生错误:', insertError);
            }
          } else {
            logger.info('❌ 无法找到可插入的位置');
          }
          
          sendResponse({ 
            success: true, 
            handled: true,
            inserted: !!targetElement,
            targetType: targetElement ? targetElement.tagName : null
          });
          return true;
          
        case 'contentScriptReady':
          logger.info('收到初始化完成消息（全局）');
          sendResponse({ success: true });
          return true;
          
        case 'test':
          logger.info('收到测试消息');
          sendResponse({ success: true, message: '测试成功' });
          return true;
          
        case 'showPageNotification':
          logger.info('显示页面通知:', request.title, request.message);
          // 创建简单的页面通知
          const notification = document.createElement('div');
          notification.className = 'smartinput-page-notification';
          notification.innerHTML = `
            <div class="smartinput-notification-title">${request.title}</div>
            <div class="smartinput-notification-message">${request.message}</div>
          `;
          
          notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #333;
            color: white;
            padding: 15px;
            border-radius: 8px;
            font-size: 14px;
            z-index: 10000;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            max-width: 300px;
            word-wrap: break-word;
          `;
          
          document.body.appendChild(notification);
          
          setTimeout(() => {
            if (notification.parentNode) {
              notification.remove();
            }
          }, 3000);
          
          sendResponse({ success: true });
          return true;
          
        default:
          logger.log('未知消息类型（全局）:', request.action);
          sendResponse({ success: true });
          return true;
      }
    }
    
    // 如果已经初始化，不处理消息，让SmartInputContent处理
    if (window.smartInputInitialized) {
      logger.info('SmartInputContent已初始化，跳过全局处理');
      return false;
    }
    
    // 如果SmartInputContent未初始化，也不处理消息
    logger.info('SmartInputContent未初始化，但跳过全局处理');
    return false;
  });

  // 初始化内容脚本
  try {
    globalSmartInput = new SmartInputContent();
  } catch (error) {
    logger.error('SmartInputContent初始化失败:', error);
  }
} 